package com.organic.maynard.outliner.model;

import static com.organic.maynard.outliner.util.preferences.Preferences.BOTTOM_MARGIN;
import static com.organic.maynard.outliner.util.preferences.Preferences.LEFT_MARGIN;
import static com.organic.maynard.outliner.util.preferences.Preferences.MAIN_WINDOW_H;
import static com.organic.maynard.outliner.util.preferences.Preferences.MAIN_WINDOW_W;
import static com.organic.maynard.outliner.util.preferences.Preferences.MAIN_WINDOW_X;
import static com.organic.maynard.outliner.util.preferences.Preferences.MAIN_WINDOW_Y;
import static com.organic.maynard.outliner.util.preferences.Preferences.RIGHT_MARGIN;
import static com.organic.maynard.outliner.util.preferences.Preferences.TOP_MARGIN;

import java.awt.Dimension;
import java.awt.Point;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import com.organic.maynard.outliner.Outliner;

public class OutlinerModel {
	
	private Logger LOGGER = Logger.getLogger("OutlinerModel");
	private Preferences preferences = Preferences.userNodeForPackage(OutlinerModel.class);
	
	public Preferences getPreferences() { return preferences; }
	
	public Integer getMainWindowWidth() {
		return preferences.getInt(MAIN_WINDOW_W, 600);
	}
	
	public void setMainWindowWidth(Integer width) {
		preferences.putInt(MAIN_WINDOW_W, width);
	}
	
	public Integer getMainWindowHeight() {
		return preferences.getInt(MAIN_WINDOW_H, 600);
	}
	
	public void setMainWindowHeight(Integer height) {
		LOGGER.info("Main Window Height set to: " + height);
		preferences.putInt(MAIN_WINDOW_H, height);
	}
	
	public Integer getMainWindowXPosition() {
		return preferences.getInt(MAIN_WINDOW_X, 100);
	}
	
	public void setMainWindowXPosition(Integer x) {
		preferences.putInt(MAIN_WINDOW_X, x);
	}
	
	public Integer getMainWindowYPosition() {
		return preferences.getInt(MAIN_WINDOW_Y, 0);
	}
	
	public void setMainWindowYPosition(Integer y) {
		preferences.putInt(MAIN_WINDOW_Y, y);
	}
	
	public int getRecentFileListMaximumSize() { return preferences.getInt("recent.files.list.max-size", 4); }
	public int getIndent() { return preferences.getInt("display.int", 15); }
	
	public Margins getOutlineMargins() {
		return new Margins(
				preferences.getInt(TOP_MARGIN, 5),
				preferences.getInt(BOTTOM_MARGIN, 5),
				preferences.getInt(LEFT_MARGIN, 5),
				preferences.getInt(RIGHT_MARGIN, 5)
				);
	}
		
	public void savePreferences() {
		try {
			preferences.sync();
		} catch (BackingStoreException bse) {
			LOGGER.severe("Failed to save Preferences: " + bse.getMessage());
		}
	}
	
	public void savePreferences(Outliner o) {
		LOGGER.info("Save Preferences called");
		Dimension d = o.getSize();
		Point p = o.getLocation();
		setMainWindowWidth(Double.valueOf(d.getWidth()).intValue());
		setMainWindowHeight(Double.valueOf(d.getHeight()).intValue());
		savePreferences();
	}
}
